package tree.tree2.symmetry.Ancestor;

import tree.TreeNode;

/**
 * @ClassName BinarySearchTreeLowestCommonAncestor
 * @Description TODO
 * @Author lenovo
 * @Date 2023-05-08 11:16
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class BinarySearchTreeLowestCommonAncestor {

    /**
     * 二叉搜索树的公共祖先
     *       4
     *    1    5
     * 2    3
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val > p.val && root.val > q.val) {
            lowestCommonAncestor(root.right, p, q);
        } else if (root.val < p.val && root.val < q.val) {
            lowestCommonAncestor(root.left, p, q);
        } else {
            return root;
        }
        return null;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(1);
        root.right = new TreeNode(5);
        BinarySearchTreeLowestCommonAncestor binarySearchTreeLowestCommonAncestor = new BinarySearchTreeLowestCommonAncestor();
        System.out.println(binarySearchTreeLowestCommonAncestor.lowestCommonAncestor(root, root.left, root.right));
    }

}